package leetcode;

import util.ListNode;

import java.math.BigInteger;

/**
 * @Project : algorithm-learning-java
 * @Author : Ruoyu Wang
 * @User : Momenta
 * @DateTime : 2024/2/27 17:32
 */

public class Q0445 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        BigInteger x1 = new BigInteger("0");
        BigInteger x2 = new BigInteger("0");

        ListNode p = l1;
        while (p != null) {
            x1 = x1.multiply(new BigInteger("10")).add(new BigInteger(String.valueOf(p.val)));
            p = p.next;
        }

        p = l2;
        while (p != null) {
            x2 = x2.multiply(new BigInteger("10")).add(new BigInteger(String.valueOf(p.val)));
            p = p.next;
        }

        BigInteger sum = x1.add(x2);

        ListNode s = new ListNode(-1, x1.toString().length() >= x2.toString().length() ? l1 : l2);
        p = s;

        String str = sum.toString();
        for (int i = 0; i < str.length(); i++) {
            if (p.next == null) {
                p.next = new ListNode(-1);
            }
            p.next.val = str.charAt(i) - '0';
            p = p.next;
        }

        return s.next;
    }
}
